/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xuidemo.provider;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.app.Context;
import ohos.media.image.common.Rect;
import com.isotne.glidelibrary.utils.OhosGlide;
import com.xuexiang.xui_lib.component.imageview.nine.ItemImageClickListener;
import com.xuexiang.xui_lib.component.imageview.nine.NineGridImageView;
import com.xuexiang.xui_lib.component.imageview.nine.NineGridImageViewAdapter;
import com.xuexiang.xuidemo.ResourceTable;
import com.xuexiang.xuidemo.item.ImageViewInfo;
import com.xuexiang.xuidemo.item.NineGridInfo;
import java.util.List;

import static com.xuexiang.xui_lib.util.DisplayUtils.getDisplayHeightInPx;
import static com.xuexiang.xuidemo.util.DisplayUtils.getDisplayWidthInPx;

/**
 * @since 2021-04-15
 */
public class XulNineGridListProvider extends BaseItemProvider {
    private List<NineGridInfo> list;
    private AbilitySlice slice;

    public XulNineGridListProvider(List<NineGridInfo> list, AbilitySlice slice) {
        this.list = list;
        this.slice = slice;
    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public Object getItem(int position) {
        if (list != null && position >= 0 && position < list.size()) {
            return list.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
        final Component cpt;
        NineGridHolder holder;
        NineGridInfo nineGridInfo = list.get(position);
        int displayHeight =  getDisplayHeightInPx(slice);
        int displayWidth = getDisplayWidthInPx(slice);
        if (convertComponent == null) {
            cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_grid_list_item, null, false);
            holder = new NineGridHolder(cpt);
            // 将获取到的子组件信息绑定到列表项的实例中
            cpt.setTag(holder);
        } else {
            cpt = convertComponent;
            holder = (NineGridHolder) cpt.getTag();
        }
        holder.bind(nineGridInfo);
        NineGridImageViewAdapter<ImageViewInfo> mAdapter = new NineGridImageViewAdapter<ImageViewInfo>() {
            /**
             * 图片加载
             *
             * @param context
             * @param imageView
             * @param imageViewInfo 图片信息
             */

            @Override
            protected void onDisplayImage(Context context, Image imageView, ImageViewInfo imageViewInfo) {
                 OhosGlide.with(slice).load(imageViewInfo.getUrl()).def(ResourceTable.Media_xui_ic_no_img).into(imageView);

            }

            @Override
            protected Image generateImageView(Context context) {
                return super.generateImageView(context);
            }
        };
        holder.mTvContent.setText(nineGridInfo.getContent());
        holder.mNglContent.setAdapter(mAdapter);
        holder.mNglContent.setItemImageClickListener(new ItemImageClickListener<ImageViewInfo>() {
            @Override
            public void onItemImageClick(Image imageView, int index, List<ImageViewInfo> list) {
                holder.computeBoundsBackward(list);//组成数据
                if (displayWidth < displayHeight) {
                    if (list.get(index).getVideoUrl() == null) {
                        Intent intent = new Intent();
                        Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(slice.getBundleName())
                            .withAbilityName("com.xuexiang.xuidemo.slice.imageview.preview.BannerNineGridPagerAbility")
                            .build();
                        intent.setParam("position", position + "");
                        intent.setParam("index", index + "");
                        intent.setOperation(operation);
                        slice.startAbility(intent);
                        slice.setTransitionAnimation(0, 0);
                    } else {
                        Intent intent = new Intent();
                        Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(slice.getBundleName())
                            .withAbilityName("com.xuexiang.xuidemo.slice.imageview.preview.BannerNineGridVideoPagerAbility")
                            .build();
                        intent.setParam("position", position + "");
                        intent.setParam("index", index + "");
                        intent.setOperation(operation);
                        slice.startAbility(intent);
                        slice.setTransitionAnimation(0, 0);
                    }
                }else{
                    return;
                }
            }
        });
        return cpt;
    }

    public static class NineGridHolder {
        private NineGridImageView<ImageViewInfo> mNglContent;
        private Text mTvContent;

        public NineGridHolder(Component itemView) {
            mTvContent = (Text) itemView.findComponentById(ResourceTable.Id_tv_content);
            mNglContent = (NineGridImageView<ImageViewInfo>) itemView.findComponentById(ResourceTable.Id_ngl_images);
            /**
             * 图片加载
             *
             * @param context
             * @param imageView
             * @param imageViewInfo 图片信息
             */
            NineGridImageViewAdapter<ImageViewInfo> mAdapter = new NineGridImageViewAdapter<ImageViewInfo>() {
                /**
                 * 图片加载
                 *
                 * @param context
                 * @param imageView
                 * @param imageViewInfo 图片信息
                 */

                @Override
                protected void onDisplayImage(Context context, Image imageView, ImageViewInfo imageViewInfo) {
                    OhosGlide.with(context).load(imageViewInfo.getUrl()).def(ResourceTable.Media_xui_ic_no_img).into(imageView);
                }

                @Override
                protected Image generateImageView(Context context) {
                    return super.generateImageView(context);
                }
            };
            mNglContent.setAdapter(mAdapter);
            mNglContent.setItemImageClickListener(new ItemImageClickListener<ImageViewInfo>() {
                @Override
                public void onItemImageClick(Image imageView, int index, List<ImageViewInfo> list) {
                    computeBoundsBackward(list);//组成数据
                }
            });
        }

        /**
         * 查找信息
         *
         * @param list 图片集合
         */
        private void computeBoundsBackward(List<ImageViewInfo> list) {
            for (int i = 0; i < mNglContent.getChildCount(); i++) {
                Component itemView = mNglContent.getComponentAt(i);
                Rect bounds = new Rect();
                if (itemView != null) {
                    Image thumbView = (Image) itemView;
                    //thumbView.getGlobalVisibleRect(bounds);
                }
                list.get(i).setmBounds(bounds);
                list.get(i).setUrl(list.get(i).getUrl());
            }

        }

        public void bind(NineGridInfo gridInfo) {
            mNglContent.setImagesData(gridInfo.getImgUrlList(), gridInfo.getSpanType());
            mTvContent.setText(gridInfo.getContent());
        }
    }
}
